package by.wind.drebedengi;

import java.util.ArrayList;
import java.util.Calendar;

import com.j256.ormlite.android.apptools.OrmLiteBaseActivity;
import com.j256.ormlite.dao.RuntimeExceptionDao;

import by.wind.drebedengi.asynctask.AsyncTaskManager;
import by.wind.drebedengi.asynctask.UploadAsyncTask;
import by.wind.drebedengi.database.MyDatabaseHelper;
import by.wind.drebedengi.datalayer.Constants;
import by.wind.drebedengi.datalayer.bean.Category;
import by.wind.drebedengi.datalayer.bean.Currency;
import by.wind.drebedengi.datalayer.bean.Place;
import by.wind.drebedengi.datalayer.bean.Record;
import by.wind.drebedengi.utils.Convertor;
import by.wind.drebedengi.utils.PrefUtil;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Spinner;
import android.widget.Toast;

public class OutgoingActivity extends OrmLiteBaseActivity<MyDatabaseHelper>  {

	private static String TAG = "Drebedengi";
    private static final int RESULT_SPEECH_TO_TEXT = 0;
    
    private static int CURRENT_HOUR = 23;
    private static int CURRENT_MINUTE = 59;
    private static int CURRENT_SECOND = 59;
    
    private Spinner itsCategoryView;
    private Spinner itsCurrencyView; 
    private Spinner itsPlaceView;
    private EditText itsTag;
    private EditText itsSum;
    
    private AsyncTaskManager itsAsyncTaskManager;
    
    private ArrayList<Category> itsCategoryList = new ArrayList<Category>();
    private ArrayList<Currency> itsCurrencyList = new ArrayList<Currency>();
    private ArrayList<Place>    itsPlaceList    = new ArrayList<Place>();
    
    /**
     * Called when the activity is first created.
     * @param savedInstanceState If the activity is being re-initialized after 
     * previously being shut down then this Bundle contains the data it most 
     * recently supplied in onSaveInstanceState(Bundle). <b>Note: Otherwise it is null.</b>
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
		Log.i(TAG, "onCreate");
        setContentView(R.layout.outgoing_tab);

        itsAsyncTaskManager = new AsyncTaskManager(this, (MainActivity)this.getParent());
		itsAsyncTaskManager.handleRetainedTask(getLastNonConfigurationInstance());
        
        ImageButton btn = (ImageButton) findViewById(R.id.speaking_button);
        btn.setOnClickListener( new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				try {
				Intent speechIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
				speechIntent.putExtra(RecognizerIntent.ACTION_RECOGNIZE_SPEECH, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
				speechIntent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Можно мяукать сейчас");
				startActivityForResult(speechIntent, RESULT_SPEECH_TO_TEXT);
				}
				catch(ActivityNotFoundException e) {
					Toast.makeText(v.getContext(), "Activity not found", Toast.LENGTH_LONG).show();
				}
				
			}
		});
        
        Button saveButton = (Button) findViewById(R.id.saveButton);
        saveButton.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				/* Datetime */
				
		        DatePicker datePicker = (DatePicker) findViewById(R.id.datePickerOutgoing);
		        Calendar calendar = Calendar.getInstance();
		        calendar.set(Calendar.DAY_OF_MONTH, datePicker.getDayOfMonth());
		        calendar.set(Calendar.MONTH, datePicker.getMonth());
		        calendar.set(Calendar.YEAR, datePicker.getYear());
		        calendar.set(Calendar.HOUR_OF_DAY, CURRENT_HOUR);
		        calendar.set(Calendar.MINUTE, CURRENT_MINUTE);
		        calendar.set(Calendar.SECOND, CURRENT_SECOND);
		        itsTag = (EditText) findViewById(R.id.tagTextView);
		        itsSum = (EditText) findViewById(R.id.sumTextView);
		        if (itsSum.getText().length() == 0) {
		        	showTraces(getString(R.string.emptysum_message));
		        	return;
		        } else if (itsCategoryView.getSelectedItem()== null) {
		        	showTraces(getString(R.string.outgoing_emptycategory_message));
		        	return;
		        } else if (itsPlaceView.getSelectedItem()== null) {
		        	showTraces(getString(R.string.emptyplace_message));
		        	return;
		        }
		        	
		        String typeString = "";
		        if (itsCategoryView.getSelectedItem()!= null)
		        	typeString = itsCategoryView.getSelectedItem().toString();
		        Record record = new Record();
		        record.setOperation_date(calendar.getTime());
		        record.setComment(itsTag.getText().toString());
		        record.setSum(-Long.valueOf(itsSum.getText().toString()) * Record.QUALIFICATION);
		        record.setCategory(retrieveCategoryByName(typeString.trim()));
		        record.setOperation_type(Constants.OPERATION_WASTLE);
		        String placeString = "";
		        if (itsPlaceView.getSelectedItem()!= null) {
		        	placeString = itsPlaceView.getSelectedItem().toString();
		        }
		        record.setPlace(retrievePlaceByName(placeString));
		        if (itsCurrencyView.getSelectedItem() != null)
		        	record.setCurrency(retrieveCurrencyByName(itsCurrencyView.getSelectedItem().toString()));
		        else
		        	showTraces(getString(R.string.emptycurrency_message));
		        getHelper().save(record);
		        resetForm();
		        itsAsyncTaskManager.setupTask(new UploadAsyncTask(OutgoingActivity.this));
			}
		});
        loadFormData();
    }
    
    private void resetForm() {
    	//save current state of currency
    	PrefUtil.saveSpinnerState(this, itsCurrencyView);
    	itsCategoryView.setSelection(0);
    	itsTag.setText(null);
    	itsSum.setText(null);
    }
    
    // set the category by speach
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    	if (requestCode == RESULT_SPEECH_TO_TEXT && resultCode == RESULT_OK) {
    		ArrayList<String> matches = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
    		String[] categoryArray = new String[itsCategoryList.size()];
    		int count = 0;
    		for(Category element : itsCategoryList) {
    			categoryArray[count] = element.getName();
    			count++;
    		}
    		itsCategoryView.setSelection(Convertor.getCategoryId(categoryArray, matches.get(0)));
    	}
    }
    
    protected void loadFormData() {
    	Log.e(TAG, "OutgoingActivity.loadFormData()");
    	RuntimeExceptionDao<Category,Integer> categoryDao = getHelper().getCategoryDataDao();
    	itsCategoryList = (ArrayList<Category>) categoryDao.queryForAll();
    	String[] items = new String[itsCategoryList.size()];
    	for(int i = 0; i<itsCategoryList.size(); i++)
    		items[i] = itsCategoryList.get(i).getName();
    	ArrayAdapter<String> adapter = new ArrayAdapter<String>(OutgoingActivity.this, android.R.layout.simple_spinner_item, items);
    	itsCategoryView = (Spinner) findViewById(R.id.outgoing_spinnerCategory);
    	adapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
    	itsCategoryView.setAdapter(adapter);
    	
    	RuntimeExceptionDao<Place,Integer> placeDao = getHelper().getPlaceDataDao();
    	itsPlaceList = (ArrayList<Place>) placeDao.queryForAll();
    	String[] placeItems = new String[itsPlaceList.size()];
    	for(int i = 0; i<itsPlaceList.size(); i++) {
    		placeItems[i] = itsPlaceList.get(i).getName();
    	}
    	ArrayAdapter<String> placeAdapter = new ArrayAdapter<String>(OutgoingActivity.this, android.R.layout.simple_spinner_item, placeItems);
    	placeAdapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
    	itsPlaceView = (Spinner) findViewById(R.id.outgoing_spinnerPlace);
    	itsPlaceView.setAdapter(placeAdapter);
    	
    	RuntimeExceptionDao<Currency,Integer> currencyDao = getHelper().getCurrencyDataDao();
    	itsCurrencyList = (ArrayList<Currency>)currencyDao.queryForAll();
    	String[] currencyItems = new String[itsCurrencyList.size()];
    	for(int i = 0; i<itsCurrencyList.size(); i++) {
    		currencyItems[i] = itsCurrencyList.get(i).getName();
    	}
    	ArrayAdapter<String> currencyAdapter = new ArrayAdapter<String>(OutgoingActivity.this, android.R.layout.simple_spinner_item, currencyItems);
    	currencyAdapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
    	itsCurrencyView = (Spinner) findViewById(R.id.outgoing_spinnerCurrency);
    	itsCurrencyView.setAdapter(currencyAdapter);
    	// restore current currency from SharedPreferences
    	itsCurrencyView.setSelection(PrefUtil.loadSpinnerState(this, itsCurrencyView));
    	
    }
    
    private Category retrieveCategoryByName(String aName) {
    	for(Category element : itsCategoryList) {
    		if (element != null && element.getName().equals(aName))
    			return element;
    	}
    	return null;
    }
    
    private Currency retrieveCurrencyByName(String aName) {
    	for(Currency element : itsCurrencyList) {
    		if (element != null && element.getName().equals(aName))
    			return element;
    	}
    	return null;
    }
    
    private Place retrievePlaceByName(String aName) {
    	for(Place element : itsPlaceList) {
    		if (element != null && element.getName().equals(aName))
    			return element;
    	}
    	return null;
    }
    
    private void showTraces(String log) {
    	(Toast.makeText(this, log, Toast.LENGTH_LONG)).show();
    }
    
    @Override
    public Object onRetainNonConfigurationInstance() {
		return itsAsyncTaskManager.retainTask();
    }
}

